import { ElMessage } from 'element-plus'

export default function useTableData(apiFunc: any, apiFuncName: string) {
  // 分页器每页个数配置组
  const defaultTablePageSize = [10, 20]

  // 数据表格
  const tableData = reactive({
    list: [],
    total: 0,
    isLoading: false
  })

  // 数据表格基本请求参数
  const tableParams = reactive({
    currentPageNo: 1,
    onePageCount: 10
  })

  // 其他参数
  let tableOtherParams = {}

  // 获取数据
  const handleTableQuery = () => {
    if (apiFunc && apiFuncName) {
      tableData.isLoading = true
      apiFunc[apiFuncName]({
        ...tableParams,
        ...tableOtherParams
      })
        .then((res: any) => {
          tableData.isLoading = false
          tableData.list = res.data.list
          tableData.total = res.data.tp.RecordAllCount
        })
        .catch(() => {
          tableData.isLoading = false
        })
    } else {
      ElMessage.warning(`useTableData：请配置基础api！`)
    }
  }

  // 重置请求
  const handleTableReset = (params: any) => {
    tableOtherParams = params
    tableParams.currentPageNo = 1
    tableParams.onePageCount = 10
    handleTableQuery()
  }

  // 设置查询参数
  const setParams = (params: any) => {
    tableOtherParams = params
    handleTableQuery()
  }

  // 设置分页
  // 如果传入了 current-page，必须监听 current-page 变更的事件（@update:current-page），否则分页切换不起作用
  const setCurrentPage = (current: number) => {
    tableParams.currentPageNo = current
    handleTableQuery()
  }

  const handleTableInit = () => {
    tableData.isLoading = false
    tableData.list = []
    tableOtherParams = {}
    tableParams.currentPageNo = 1
    tableParams.onePageCount = 10
  }

  return {
    defaultTablePageSize,
    tableData,
    tableParams,
    setParams,
    setCurrentPage,
    handleTableReset,
    handleTableInit
  }
}
